package com.yunji.framework_template.common.http;

import java.io.UnsupportedEncodingException;

import com.yunji.framework_template.common.constant.Constant;
import com.yunji.framework_template.common.log.LoggerWrapper;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * base64加密 解密
 * 
 * @author yangbo
 */
@SuppressWarnings("restriction")
public class Base64Helper {

    private static final LoggerWrapper logger = LoggerWrapper.getLogger(Base64Helper.class);

    /**
     * Base64加密
     * 
     * @param str
     * @return
     */
    public static String encode(String str) {
        if (str == null) {
            return str;
        }
        try {
            return new BASE64Encoder().encode(str.getBytes(Constant.CHARSET));
        } catch (UnsupportedEncodingException e) {
        }
        return null;
    }

    /**
     * Base64加密
     * 
     * @param bt
     * @return
     */
    public static String encode(byte[] bt) {
        if (bt == null) {
            return null;
        }
        return new BASE64Encoder().encode(bt);
    }

    /**
     * Base64字符串解密
     * 
     * @param s
     * @return
     */
    public static String decode(String s) {
        byte[] b = null;
        String result = null;
        try {
            if (s != null) {
                BASE64Decoder decoder = new BASE64Decoder();
                b = decoder.decodeBuffer(s);
                result = new String(b, Constant.CHARSET);
            }
        } catch (Exception e) {
            logger.error("base64 decode exception happened:" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * Base64字符串解密
     * 
     * @param s
     * @return
     */
    public static byte[] decodeToByteArr(String s) {
        try {
            if (s != null) {
                return new BASE64Decoder().decodeBuffer(s);
            }
            return null;
        } catch (Exception e) {
            logger.error("base64 decode exception happened:" + e.getMessage(), e);
            return null;
        }
    }
}
